import axios from 'axios'
import { Message } from 'element-ui'
import { getHeader } from '@/app.config'
import store from '@/store'
import { getToken, removeToken, removeName } from '@/utils/auth'

let service = axios.create({
  baseURL: process.env.VUE_APP_KANBAN_HOST, 
  timeout: 600000, // request timeout
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers = getHeader()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use((response) => {
  let res = response
  if(response.status == 200 && res.data.code == 200) {        
    return res.data
  } else if(response.status == 200 && res.data.code == 401) {
    removeToken()
    removeName()
    window.location.href = '/#/login'
    Message.error('登陆超时或该账号已被登出，请您重新登录');
    return Promise.reject(res)
  } else if(response.status == 200 && res.data.code == 403) {
    window.location.href = '/#/'    
    Message.error('您暂无权限，请先申请权限');
    return Promise.reject(res)
  } else if(response.status == 200 && res.data.code == 400) {
    Message({
      showClose: true,
      message: res.data.msg,
      type: 'error'
    })
    return res.data 
  } else if(response.status == 200 && res.data.code == 500) {
    //Message.error(res.msg);
    // Message({
    //   showClose: true,
    //   message: res.data.msg,
    //   type: 'error'
    // })
    return res.data   
  } else {
    //Message.error(res.msg);
    // Message({
    //   showClose: true,
    //   message: res.data.msg,
    //   type: 'error'
    // })
    return Promise.reject(res)    
  }
},(error) => {
  let res = error.response;
  Message.error(res.statusText);
  return Promise.reject(error);
})

export default service